package com.baizhi.Aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class VideoAOP {

    private static final Logger log = LoggerFactory.getLogger(VideoAOP.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;  //对字符串支持比较友好,不能存储对象
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(com.baizhi.Annotation.VideoRedis)")
    public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("进入切面");


        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        StringBuilder sb = new StringBuilder();
        //获取类的权限定类名
        String name = joinPoint.getTarget().getClass().getName();
        sb.append(name);
        sb.append("&");
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            sb.append(arg);
        }
        String s = sb.toString();
        System.out.println("s = " + s);

        HashOperations hashOperations = redisTemplate.opsForHash();

        //判断key是否存在
        Boolean aBoolean = hashOperations.hasKey(name, s);
        Object proceed = null;
        if (aBoolean) {
            //存在 取出缓存返回数据
            proceed = hashOperations.get(name, s);
        } else {
            proceed = joinPoint.proceed();
            hashOperations.put(name, s, proceed);
        }

        return proceed;
    }

}